// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  
  try {
    // 检查用户权限（只有管理员可以批量创建宿舍）
    const userInfo = await db.collection('users').where({
      openid: wxContext.OPENID
    }).get()
    
    if (userInfo.data.length === 0 || userInfo.data[0].role !== '管理员') {
      return {
        success: false,
        error: '无权操作，只有管理员可以批量创建宿舍'
      }
    }

    // 从event参数获取要添加的宿舍数据
    const { dormsData } = event
    if (!dormsData || !Array.isArray(dormsData) || dormsData.length === 0) {
      return {
        success: false,
        message: '请提供有效的宿舍数据数组'
      }
    }

    const results = [];
    const now = new Date();

    for (const dorm of dormsData) {
      try {
        // 验证必要字段
        if (!dorm.building || !dorm.roomNo) {
          results.push({
            building: dorm.building,
            roomNo: dorm.roomNo,
            success: false,
            message: '楼栋号和房间号为必填项'
          });
          continue;
        }

        // 1. 检查宿舍是否已存在 (避免重复创建)
        const exist = await db.collection('dorms').where({
          building: dorm.building,
          roomNo: dorm.roomNo
        }).count();

        if (exist.total > 0) {
          results.push({
            building: dorm.building,
            roomNo: dorm.roomNo,
            success: false,
            message: '宿舍已存在，跳过添加'
          });
          console.log(`宿舍 ${dorm.building}栋-${dorm.roomNo} 已存在，跳过。`);
          continue;
        }

        // 2. 准备要存入数据库的完整数据
        const dormToCreate = {
          building: dorm.building,
          roomNo: dorm.roomNo,
          members: Array.isArray(dorm.members) ? dorm.members : [],
          monitorId: dorm.monitorId || '',
          currentScore: typeof dorm.currentScore === 'number' ? dorm.currentScore : 80, // 默认80分
          scoreHistory: Array.isArray(dorm.scoreHistory) ? dorm.scoreHistory : [],
          images: Array.isArray(dorm.images) ? dorm.images : [],
          medals: Array.isArray(dorm.medals) ? dorm.medals : 
                 (dorm.currentScore >= 90 ? ['优秀宿舍'] : []),
          createTime: now,
          updateTime: now,
          creatorId: userInfo.data[0]._id,
          creatorName: userInfo.data[0].name
        };

        // 3. 添加数据到数据库
        const addResult = await db.collection('dorms').add({
          data: dormToCreate
        });
        
        results.push({
          building: dorm.building,
          roomNo: dorm.roomNo,
          success: true,
          _id: addResult._id
        });
        
        console.log(`宿舍 ${dorm.building}栋-${dorm.roomNo} 添加成功，ID: ${addResult._id}`);

      } catch (singleError) {
        results.push({
          building: dorm.building,
          roomNo: dorm.roomNo,
          success: false,
          message: singleError.message
        });
        console.error(`处理宿舍 ${dorm.building}栋-${dorm.roomNo} 失败:`, singleError);
      }
    }
    
    const successCount = results.filter(r => r.success).length;
    const failCount = results.filter(r => !r.success).length;
    
    return {
      success: true,
      message: `批量添加宿舍操作完成。成功添加 ${successCount} 个，失败或跳过 ${failCount} 个。`,
      results
    };
    
  } catch (error) {
    console.error('批量创建宿舍失败', error);
    return {
      success: false,
      message: '批量创建宿舍失败',
      error: error.message
    };
  }
} 